<template>
  <div class="container">
    <div class="content-wrapper">
      <el-table
        ref="multipleTableRef"
        :data="cart"
        height="700"
        element-loading-text="正在加载数据..."
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="selectable" width="55" align="center" />
        <el-table-column label="商品图片" width="200" align="center">
          <template #default="scope">
            <div class="image-container">
              <img :src="`/api/public/findgoodsimg/${scope.row.goods.gid}`" alt="商品图片" />
            </div>
          </template>
        </el-table-column>
        <el-table-column property="goods.bookname" label="商品名称" width="200" align="center"></el-table-column>
        <el-table-column property="num" label="商品数量" width="150" align="center" />
        <el-table-column property="price" label="商品单价" width="150" align="center" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="danger"
              @click="del(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="button-container">
        <el-checkbox v-model="isChecked" @change="handleCheckAllChange">全选</el-checkbox>
        <span>总价: {{ totalPrice }}</span>
        <el-button @click="add()" type="danger">立即购买</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref, toRefs, computed } from 'vue'
import { $get, $postf, $postj } from "../../ajax/index.js"
import myalert from "../../utils/myalert.js"
import store from "../../store/index.js"
import { useRoute, useRouter } from 'vue-router'

// 定义商品项类型
interface CartItem {
  id: number;
  goods: {
    gid: number;
    bookname: string;
  };
  num: number;
  price: number;
}

// 封装 API 请求
const fetchCartData = async () => {
  try {
	  const fd=new FormData
	  fd.append("uid",store.state.user.uid)
    const resp = await $postf("/api/seller/cart/finduid",fd)
    return resp.data.data as CartItem[]
  } catch (error) {
    console.error("获取购物车数据失败:", error)
    myalert('获取购物车数据失败，请稍后重试')
    return []
  }
}

const deleteCartItem = async (id: number) => {
  try {
    const resp = await $get(`/api/seller/cart/del/id=${id}`)
    return resp.data.success
  } catch (error) {
    console.error('删除商品请求出错:', error)
    myalert('删除商品请求出错，请稍后重试')
    return false
  }
}

const data = reactive({
  cart: [] as CartItem[], // 购物车
  total: 0, // 总价
})

const { cart } = toRefs(data)

const multipleTableRef = ref(null)
const isChecked = ref(false)
const selectedGoods = ref<CartItem[]>([])

// 定义 selectable 函数，这里简单返回 true，可根据实际需求修改
const selectable = () => true

// 挂载
onMounted(async () => {
  data.cart = await fetchCartData()
})

async function del(id: number) {
  const success = await deleteCartItem(id)
  if (success) {
    // 从购物车中移除该商品
    data.cart = data.cart.filter(item => item.id!== id)
    // 更新选中商品列表
    selectedGoods.value = selectedGoods.value.filter(item => item.id!== id)
    // 重新计算总价
    handleSelectionChange(selectedGoods.value)
  }
}

// 实现立即购买的逻辑
const router = useRouter()
function add() {
  if (selectedGoods.value.length > 0) {
	  let fd=new FormData();
	  fd.append("uid",store.state.user.uid)
	  fd.append("amount",data.total)
	  fd.append("pay_status",0)
	  fd.append("ship_status",0)
	  fd.append("ship2name",store.state.user.uname)
	  fd.append("ship2phone",store.state.user.phone)
	  fd.append("ship2addr",store.state.user.addr)
	  $postf("/api/seller/order",fd)
	    .then((resp) => {
			
	    })
    const goodsData = selectedGoods.value.map(item => ({
      id: item.id,
	  uid:item.uid,
      goods: item.goods,
      num: item.num,
      price: item.price
    }))
    $postj("/api/seller/orditem", goodsData)
      .then(() => {
        router.push("/order")
      })
  } else {
    console.log('请选择要购买的商品')
    myalert('请选择要购买的商品')
  }
}

const handleCheckAllChange = (checked: boolean) => {
  if (multipleTableRef.value) {
    multipleTableRef.value.toggleAllSelection()
  }
}

const handleSelectionChange = (selection: CartItem[]) => {
  // 计算选中商品的总价
  const total = selection.reduce((acc, item) => {
    return acc + item.num * item.price
  }, 0)
  data.total = total
  selectedGoods.value = selection
}

const totalPrice = computed(() => data.total)
</script>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
}

.content-wrapper {
  text-align: center;
}

.image-container {
  width: 10vw;
  height: 10vw;
  margin: 0 auto;
}

.image-container img {
  height: 98%;
  width: 100%;
}

.button-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}
</style>    